package artibella.media.audio 
{
	import artibella.media.AList;
	import artibella.media.AListItem;
	import artibella.media.APlayer;
	import artibella.media.audio.AudioMedia;
	import artibella.media.audio.AudioMediaParameters;
	import artibella.media.controls.AController;
	import artibella.media.controls.AudioController;
	
	/**
	 * ...
	 * @author pbordachar
	 */
	
	public class AudioPlayer extends APlayer
	{
		private var _currentMedia:AudioMedia;

		public function AudioPlayer() 
		{
			super();
		}
		
		// - - -
		
		override public function set controller( c:AController ):void
		{
			_controller = ( c != null ) ? c : new AudioController();
			_controller.player = this;
			_controller.init();
			_view.addChild( _controller );
		}
		
		///////  L I S T

		override public function addListItem( u:String, t:String = "", p:String = "" ):void
		{
			if ( _list == null ) _list = new AList( true );
			
			_list.addItem( new AudioListItem( u, t, p ) );
		}
		

		// - - -
		
		override public function previous():void
		{
			var item:AListItem = _list.getPreviousItem();
			
			_playMedia( item );
		}
		
		override public function next():void
		{
			var item:AListItem = _list.getNextItem();
			
			_playMedia( item );
		}
		
		///////  T R A C K
		
		override public function play( i:int = -1 ):void
		{
			if ( _list == null ) {
				//throw new Error( " AudioPlayer -- no AudioListItem added" );
				trace(" ");
				trace("AudioPlayer -- no AudioListItem added to the list");
				return;
			}
			
			var item:AListItem = ( i >= 0 ) ? _list.getItemByIndex( i ) : _list.getNextItem();
			
			_playMedia( item );
		}
		
		private function _playMedia( item:AListItem ):void
		{
			if ( item == null ) return;
			
			_killMedia();
			
			var parameters:AudioMediaParameters = new AudioMediaParameters();
			parameters.volume = _defaultVolume;
			parameters.controller = _controller;
			parameters.agent = _controller;
			
			_currentMedia = new AudioMedia( item.url, parameters );
			_currentMedia.play();
			
			// todo ?
			//if ( item.preview != "" && item.preview != _previewURL ) loadPreview( item.preview );
			
			_controller.labelText = item.label;
		}
		
		private function _killMedia():void
		{
			( _controller as AudioController).media = null;
			
			if ( _currentMedia != null ) {
				_currentMedia.dispose();
				_currentMedia = null;
			}
		}
		
		// ----- IDisposable
		
		override public function dispose():void
		{
			_killMedia();
			
			super.dispose();
		}
	}
}